package cn.kgc.service;

import cn.kgc.base.dto.LockStockDTO;
import cn.kgc.base.vo.OrderItemVo;
import cn.kgc.base.vo.OrderSpuInfoVo;
import cn.kgc.base.vo.UmsMemberReceiveAddressVo;
import cn.kgc.client.CartFeignClient;
import cn.kgc.client.PmsFeignClient;
import cn.kgc.client.UmsFeignClient;
import cn.kgc.client.WmsFeignClient;
import cn.kgc.commons.exception.HttpException;
import cn.kgc.commons.util.UserContextHolder;
import cn.kgc.commons.vo.Result;
import cn.kgc.constant.OrderStatusEnum;
import cn.kgc.constant.SourceTypeEnum;
import cn.kgc.entity.OmsOrder;
import cn.kgc.entity.OmsOrderItem;
import cn.kgc.mapper.OmsOrderItemMapper;
import cn.kgc.mapper.OmsOrderMapper;
import cn.kgc.vo.OrderSubmitVO;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.w3c.dom.stylesheets.LinkStyle;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: 石浩杰
 * @date: 2023-01-02 14:53
 */
@Service("orderService")
public class OrderServiceImpl implements OrderService {
    @Resource
    private OmsOrderMapper omsOrderMapper;

    @Resource
    private OmsOrderItemMapper omsOrderItemMapper;

    @Resource
    private CartFeignClient cartFeignClient;

    @Resource
    private UmsFeignClient umsFeignClient;

    @Resource
    private PmsFeignClient pmsFeignClient;

    @Resource
    private WmsFeignClient wmsFeignClient;
    @Override
    public String generateOrderInfo(OrderSubmitVO orderSubmitVO,long memberId,String memberUserName) {
        //保存OmsOrder数据
        OmsOrder omsOrder = getOmsOrder(orderSubmitVO,memberId, memberUserName);
        if (omsOrder==null){
            throw new HttpException(50002, HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        omsOrderMapper.insert(omsOrder);
        //保存OmsOrderItem数据
        List<OmsOrderItem> omsOrderItemList=getOmsOrderItem(omsOrder);
        if (omsOrderItemList==null){
            throw new HttpException(50002, HttpStatus.INTERNAL_SERVER_ERROR.value());
        }
        List<LockStockDTO> lockStockDTOList=new ArrayList<>();
        for (OmsOrderItem omsOrderItem : omsOrderItemList) {
            omsOrderItemMapper.insert(omsOrderItem);
            LockStockDTO lockStockDTO=new LockStockDTO();
            lockStockDTO.setAreaCode(omsOrder.getAreacode());
            lockStockDTO.setSkuId(omsOrderItem.getSkuId());
            lockStockDTO.setLockStock(omsOrderItem.getSkuQuantity());
            lockStockDTOList.add(lockStockDTO);
        }
        //锁定库存（需要的参数:skuId wareId lockStock 表:wms_ware_sku）
        Result<Boolean> result = wmsFeignClient.lockStock(lockStockDTOList);
        if (result.getData()==false){
            //分布式事务进行回滚
        }

        wmsFeignClient.lockStock(lockStockDTOList);
        return omsOrder.getOrderSn();
    }

    /**
     * 获得订单对应的商品的信息
     * @return
     */
    private List<OmsOrderItem> getOmsOrderItem(OmsOrder omsOrder){
        Result<List<OrderItemVo>> result=cartFeignClient.getOrderItemVo(omsOrder.getMemberId());
        if (result.getData()==null){//服务降级
            return null;
        }
        List<OrderItemVo> orderItemVoList=result.getData();
        //订单商品对应的SPU数据
        //方式一：获得购物车中每个商品的SpuId,根据SpuId获得SPU信息
        //选择方式二：将购物车中所有商品的SpuId进行过滤，去掉重复数据。再根据一组SpuId获得Spu信息
        HashSet<Long> spuIdSet=new HashSet<>();
        for (OrderItemVo orderItemVo:orderItemVoList){
            spuIdSet.add(orderItemVo.getSpuId());
        }
        Result<Map<Long, OrderSpuInfoVo>> result2=pmsFeignClient.getOrderSpuInfo(spuIdSet);
        if (result2==null){ //服务降级，返回空数据
            return null;
        }
        Map<Long,OrderSpuInfoVo> map=result2.getData();
        List<OmsOrderItem> omsOrderItems=orderItemVoList.stream().map(orderItemVo -> {
            OmsOrderItem omsOrderItem=new OmsOrderItem();
            //订单相关数据
            omsOrderItem.setOrderSn(omsOrder.getOrderSn());
            omsOrderItem.setOrderId(omsOrder.getId());
            //订单的sku的数据
            omsOrderItem.setSkuId(orderItemVo.getSkuId());
            omsOrderItem.setSkuName(orderItemVo.getTitle());
            omsOrderItem.setSkuQuantity(orderItemVo.getCount());
            omsOrderItem.setSkuPrice(orderItemVo.getPrice());
            omsOrderItem.setSkuPic(orderItemVo.getImage());
            String skuAttrsValue= StringUtils.collectionToDelimitedString(orderItemVo.getSkuAttr(),"-");
            omsOrderItem.setSkuAttrsVals(skuAttrsValue);
            //订单商品的积分数据
            omsOrderItem.setGiftIntegration(orderItemVo.getTotalPrice().intValue());
            omsOrderItem.setGiftGrowth(orderItemVo.getTotalPrice().intValue());
            //封装spu信息
            OrderSpuInfoVo orderSpuInfoVo=map.get(orderItemVo.getSpuId());
            omsOrderItem.setSpuId(orderSpuInfoVo.getSpuId());
            omsOrderItem.setSpuName(orderSpuInfoVo.getSpuName());
            omsOrderItem.setSpuBrand(orderSpuInfoVo.getSpuBrand());
            omsOrderItem.setSpuPic(orderSpuInfoVo.getSpuPic());
            return omsOrderItem;
        }).collect(Collectors.toList());
        return null;
    }

    private OmsOrder getOmsOrder(OrderSubmitVO orderSubmitVO,long memberId, String memberUserName) {
        //保存OmsOrder数据
        OmsOrder omsOrder=new OmsOrder();
        omsOrder.setMemberId(memberId);
        String orderSn=UUID.randomUUID().toString().replaceAll("-","");
        omsOrder.setOrderSn(orderSn);//订单编号
        //会员名
        omsOrder.setMemberUsername(memberUserName);
        //获得购物车中商品信息
        Result<List<OrderItemVo>> result=cartFeignClient.getOrderItemVo(memberId);
        BigDecimal totalPrice=new BigDecimal(0);
        if (result.getData()==null){//获得购物车中商品信息为空 服务降级
            return null;//订单信息为null
        }
        List<OrderItemVo> orderItemVoList=result.getData();
        for (OrderItemVo orderItemVo : orderItemVoList) {
            totalPrice=totalPrice.add(orderItemVo.getTotalPrice());
        }
        //订单总金额
        omsOrder.setTotalAmount(totalPrice);
        //应付金额
        omsOrder.setPayAmount(totalPrice);
        //运费金额
        omsOrder.setFreightAmount(new BigDecimal(0));
        //支付方式
        omsOrder.setPayType(orderSubmitVO.getPayType().shortValue());
        //订单来源
        omsOrder.setSourceType(SourceTypeEnum.SOURCE_TYPE_APP.getSourceType());
        //订单状态
        omsOrder.setStatus(OrderStatusEnum.NON_PAY.getOrderStatus());
        //积分
        omsOrder.setIntegration(totalPrice.intValue());
        //成长值
        omsOrder.setGrowth(totalPrice.intValue());
        //获得收货人的地址信息
        long addRID=orderSubmitVO.getAddrId();
        Result<UmsMemberReceiveAddressVo> result2=umsFeignClient.selectOne(addRID);
        if (result2.getData()==null){//获得收货人的地址信息为空 服务降级
            return null;//订单信息为null
        }
        UmsMemberReceiveAddressVo umsMemberReceiveAddressVo=result2.getData();
        omsOrder.setReceiverName(umsMemberReceiveAddressVo.getName());
        omsOrder.setReceiverPhone(umsMemberReceiveAddressVo.getPhone());
        omsOrder.setReceiverPostCode(umsMemberReceiveAddressVo.getPostCode());
        omsOrder.setReceiverProvince(umsMemberReceiveAddressVo.getProvince());
        omsOrder.setReceiverCity(umsMemberReceiveAddressVo.getCity());
        omsOrder.setReceiverRegion(umsMemberReceiveAddressVo.getRegion());
        omsOrder.setReceiverDetailAddress(umsMemberReceiveAddressVo.getDetailAddress());
        omsOrder.setAreacode(umsMemberReceiveAddressVo.getAreacode());
        return omsOrder;
    }
}
